﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace HFK.DxFluentUI.Utility
{
  public class ChildPropertySyntax
  {
    List<string> m_propertyComponents;

    public ChildPropertySyntax(string propertyName)
    {
      m_propertyComponents = new List<string>(propertyName.Split('.'));
    }

    public static ChildPropertySyntax Create<T, U>(Expression<Func<T, U>> expression)
    {
      if (!(expression.Body is MemberExpression))
      {
        throw new ArgumentException("Expression is not a member expression");
      }

      string propertyName = string.Empty;
      MemberExpression memberExpression = expression.Body as MemberExpression;
      while (memberExpression != null)
      {
        if (memberExpression.Member.MemberType != System.Reflection.MemberTypes.Property)
        {
          throw new ArgumentException("Member is not a property");
        }
        propertyName = memberExpression.Member.Name + "." + propertyName;
        memberExpression = memberExpression.Expression as MemberExpression;
      }

      return new ChildPropertySyntax(propertyName.Substring(0, propertyName.Length - 1));
    }

    public int Count
    {
      get { return m_propertyComponents.Count; }
    }

    public string PropertyName
    {
      get { return PropertyUntil(Count - 1); }
    }

    public List<string> PropertyParts
    {
      get { return m_propertyComponents; }
    }

    public string Property(int index)
    {
      return m_propertyComponents[index];
    }

    public string PropertyUntil(int index)
    {
      string returnValue = string.Empty;
      for (int i = 0; i <= index; i++)
      {
        returnValue = returnValue + "." + m_propertyComponents[i];
      }

      return returnValue.Substring(1);
    }
  }
}
